<template>
  <div class="login_container">
    <el-form
      class="login_form"
      ref="loginFormRef"
      :model="loginFormData"
      :rules="loginFormValidate"
      status-icon
      label-width="12px"
      show-required-asterisk="true"
      size="large"
      lable-position="left"
    >
      <h1>Hello</h1>
      <h2>欢迎来到安真通</h2>

      <el-form-item prop="Username" label=" ">
        <el-input
          type="text"
          placeholder="请输入用户名"
          :prefix-icon="User"
          v-model="loginFormData.Username"
        ></el-input>
      </el-form-item>
      <el-form-item prop="Password" label=" ">
        <el-input
          type="password"
          placeholder="请输入密码"
          :prefix-icon="Lock"
          v-model="loginFormData.Password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          v-loading.fullscreen.lock="fullscreenLoading"
          size="large"
          @click="handleLogin"
          >登录</el-button
        >
        <p>
          您是否已经注册？若没有，请先去
          <router-link class="registerRouter" to="/register">注册</router-link>
        </p>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
// @ts-ignore
import { User, Lock, Message, TopLeft } from "@element-plus/icons-vue";
import { ElMessage, ElNotification, FormRules } from "element-plus";
import { reactive, ref } from "vue";
import { reqLogin } from "@/api/user/index";
import useUserStore from "@/store/modules/user"; // 引入用户相关小仓库
import { useRouter, useRoute } from "vue-router"; //引入路由
import { getTime } from "@/utils/time"; // 引入获取当前时间段的函数

const loginFormRef = ref(); // 定义表单组件
const loginFormData = reactive({ Username: "", Password: "" }); // 定义表单初始数据
let fullscreenLoading = ref(false); // 定义加载效果控件
let $router = useRouter(); // 获取路由器
let route = useRoute();
let useStore = useUserStore(); //获取用户动态数据

// 定义表单验证规则
const loginFormValidate = reactive<FormRules<typeof loginFormData>>({
  Username: [
    {
      required: true,
      trigger: "blur",
      message: "请输入用户名",
    },
    {
      pattern: /^(?![0-9])[\w\u4e00-\u9fa5]{3,10}$/,
      message: "用户名必须由3-10位字符组成,且不能以数字开头",
      trigger: "blur",
    },
  ],
  Password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      pattern: /^[a-zA-Z/[a-zA-Z0-9_-]{6,18}$/,
      message: "密码必须由6-18位的字母或数字或'_'或'-'组成",
      trigger: "blur",
    },
  ],
});

// 登录函数
const handleLogin = async () => {
  // 点击登录显示加载效果
  fullscreenLoading.value = true;

  // 1、异步表单验证
  await loginFormRef.value.validate().catch((err: any) => {
    fullscreenLoading.value = false;
    ElMessage.error("用户名或密码格式不对");
    throw err;
  });

  // 2、发起登录请求
  const resData = await reqLogin(loginFormData)
    /* 请求成功执行事件 */
    .then((res) => {
      // 用户不存在或密码错误
      if (res.data.code === 7) {
        fullscreenLoading.value = false;
        ElMessage.error(res.data.msg);
        throw Error;
      }

      return res.data;
    })
    /* 请求失败执行事件 */
    .catch((error) => {
      fullscreenLoading.value = false;
      ElNotification({
        type: "error",
        title: getTime() + "好!",
        message: (error as Error).message,
        showClose: false,
      });
      throw Error;
    });

  useStore.saveToken(resData.data.token); // 保存token到pinia和本地缓存中
  let authorityId = resData.data.user.authorityId;
  localStorage.setItem("authorityId", String(authorityId));//保存当前用户的authorityId
  fullscreenLoading.value = false;
  ElMessage.success("登录成功！");
  // 路由导航守卫时，返回登录成功后，如果有想要跳转的页面，则直接跳转，否则跳转到home
  $router.push((route.query.redirect as string) || "/home");
};
</script>

<style scoped lang="scss">
.login_container {
  width: 100vw;
  height: 100vh;
  background: url("@/assets/images/background.jpg") no-repeat center/cover;
  display: flex;
  justify-content: center;
  align-items: center;
  .el-form {
    width: 340px;
    min-width: 300px;
    padding: 20px;
    .el-input {
      opacity: 0.8;
    }
    .el-button {
      width: 100%;
      height: 40px;
    }
  }
  h1 {
    color: white;
    font-size: 40px;
  }

  h2 {
    color: white;
    font-size: 20px;
    margin: 20px 0;
  }
  p {
    color: #303133;
    width: 100%;
    text-align: center;
    padding: 5px;
    .registerRouter {
      font-size: 16px;
      font-weight: bolder;
      color: #409eff;
    }
  }
}
</style>
@/api/index
